import React, { Fragment, useState, useEffect } from 'react';
import './home.less';
import './home.css';
import * as Icon from '@ant-design/icons';
import type { IRouteComponentProps } from 'umi';
import { ExportOutlined } from '@ant-design/icons';
import { history, request } from 'umi';
import {
  MailOutlined,
  CloseOutlined,
  SmileFilled,
  ExclamationOutlined,
  AuditOutlined,
  UpOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Menu, Form, Button, Input } from 'antd';
import { withRouter } from 'react-router-dom';
import { InputNumber, Table } from 'antd';
import axios from 'axios';
function loginout() {
  window.sessionStorage.clear();
  history.push('/login');
}
type MenuItem = Required<MenuProps>['items'][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: 'group',
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as MenuItem;
}
// submenu keys of first level
const Home = ({ children }: IRouteComponentProps) => {
  const [unreadMessage, setUnreadMessage] = useState();
  const Y = new Date().getFullYear();
  const M = (new Date().getMonth() + 1 + '').padStart(2, '0');
  const D = (new Date().getDate() + '').padStart(2, '0');
  const year = Y + '-' + M + '-' + D;
  const getMessage = async (start = '2023-01-01', end = year) => {
    let { data } = await axios.get(
      `http://127.0.0.1:7777/news/message/?start=${start}&end=${end}`,
    );
    let len = data.messageData.filter((item) => item.status === false);
    setUnreadMessage(len.length);
  };
  const getMoudelList = () => {
    request('/api/moulePost', {
      method: 'get',
    }).then((res) => {
      res.mouduleList.sort((a, b) => {
        return a.desc - b.desc;
      });
      console.log(res.mouduleList);
      setMenulist(res.mouduleList);
      const newdata = [];
      res.mouduleList.map((item3) => {
        item3.key = item3._id;
        if (item3.desc == res.mouduleList?.length) {
          console.log(item3);
          return false;
        }
        newdata.push(item3);
      });
      setdata(newdata);
    });
  };

  useEffect(() => {
    getMoudelList();
    getMessage();
  }, []);
  // 控制账号密码错误弹出div的显示和隐藏
  const [isModalOpen, setIsModalOpen] = useState(false); //栗鹏杰
  const [isModalOpener, setIsModalOpener] = useState(false);
  const [isPassword, setPassword] = useState(false); //密码修改框
  const handTrue = () => {
    setIsModalOpen(true);
  };
  const handFalse = () => {
    setIsModalOpen(false);
  };
  const [menuTop, setmenuTop] = useState([
    { key: '/echars', name: '销售门户' },
  ]);
  const [openKeys, setOpenKeys] = useState(['sub1']);
  const [newitems, setitems] = useState([
    getItem('日常工作', '/', <MailOutlined />),
    getItem('销售门户', '/echars', <MailOutlined />),
  ]);
  const rootSubmenuKeys = [];
  // 弹框收缩
  const [shousuo, setShousuo] = useState('usersinfocenter');
  const yincang = () => {
    if (shousuo == 'usersinfocenter') {
      setShousuo('usercenter');
    } else if (shousuo == 'usercenter') {
      setShousuo('usersinfocenter');
    }
  };

  const [userMessage, setMessage] = useState(
    JSON.parse(sessionStorage.getItem('userMessage')),
  ); //登录之后的用户信息

  // 获取任务列表
  function getask() {}
  function pushxin(e) {
    let obj = { key: e.key, name: e.domEvent.target.innerHTML };
    let menus = menuTop.filter((item) => {
      if (item.key == e.key) {
        history.push(`/home${item.key}`);
        return item;
      }
    });
    if (menus.length) return;
    menuTop.push(obj);
    setmenuTop(menuTop);
    history.push(`/home${e.key}`);
  }
  const onOpenChange: MenuProps['onOpenChange'] = (keys) => {
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (rootSubmenuKeys.indexOf(latestOpenKey!) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  };
  const [menulist, setMenulist] = useState([]); //导航菜单
  const [navTitle, setnavTitle] = useState('我的门户');
  // 关闭排序
  function handleClose() {
    setIsModalOpener(false);
  }
  function huanleftnav(_id) {
    request('/api/menuPost', {
      method: 'get',
      params: {
        _id: _id,
      },
    }).then((res) => {
      // 判断管理的弹出
      if (res.menulist.mouduleMessage.desc == 17) {
        setIsModalOpener(true);
        return false;
      }
      let newitemsList = res.menulist.menulist;
      var newitems = [];
      newitemsList.forEach((item) => {
        var itemson = [];
        if (item.menulist) {
          console.log(789);

          let itemsonson = [];
          item.menulist.forEach((ite) => {
            let newobj = { key: ite.menu_key, label: ite.menuName };
            itemsonson.push(newobj);
          });

          itemson = getItem(
            item.menuName,
            item._id,
            iconToElement(item.icon),
            itemsonson,
          );
          newitems.push(itemson);
        } else {
          itemson = getItem(
            item.menuName,
            item.menu_key,
            iconToElement(item.icon),
          );
          newitems.push(itemson);
        }
      });
      console.log(newitems);
      setitems(newitems);
      setnavTitle(res.menulist.mouduleMessage.MouduleName);
    });
  }
  const iconToElement = (name: string) =>
    React.createElement(Icon && (Icon as any)[name], {
      style: { fontSize: '16px' },
    });

  const Ondelete = (keys) => {
    if (menuTop.length == 1) {
      alert('已经是最后一页了');
      history.push('/home/echars');
      return false;
    }
    let menus = menuTop.filter((i) => i.key != keys);
    setmenuTop(menus);
    history.go(-1);
  };
  const setProps = (keys) => {
    history.push(`/home${keys}`);
  };
  // 表格头部内容
  const columns = [
    {
      title: '序号',
      width: '18%',
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '名称',
      dataIndex: 'MouduleName',
      key: 'MouduleName',
      render: (text) => <a>{text}</a>,
    },
  ];
  // 数据
  const [data, setdata] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [newselectedRowKeys, setnewselectedRowKeys] = useState([]);
  const onSelectChange = (newSelectedRowKeys, selectall) => {
    setSelectedRowKeys(newSelectedRowKeys);
    setnewselectedRowKeys(selectall[0].desc);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    hideSelectAll: true,
    type: 'radio',
  };
  // 保存数据
  function baocun() {
    // 把管理添加进去
    request('/api/moulePost', {
      method: 'get',
    }).then((res) => {
      let data1 = JSON.parse(JSON.stringify(data));
      let o = menulist[menulist.length - 1];
      data1.splice(toptotal, data1.length - toptotal);
      setMenulist([...data1, o]);
      setIsModalOpener(false);
      setnewselectedRowKeys([]);
      setSelectedRowKeys([]);
    });
  }
  // 上移
  function sahngyi() {
    if (newselectedRowKeys == 1) {
      alert('他已经是最后一个了，不能在下移了');
      return false;
    }
    data.map((item1) => {
      if (item1._id == selectedRowKeys[0]) {
        item1.desc = newselectedRowKeys - 1;
        setnewselectedRowKeys(item1.desc);
      }
    });
    data.map((item2) => {
      // console.log(item2.desc);
      if (newselectedRowKeys - 1 == item2.desc) {
        if (item2._id != selectedRowKeys[0]) {
          item2.desc = newselectedRowKeys;
        }
      }
    });
    data.sort((a, b) => {
      return a.desc - b.desc;
    });
    console.log(data);

    setdata([...data]);
  }
  // 下移
  function xiayi() {
    if (newselectedRowKeys == menulist.length - 1) {
      alert('他已经是最后一个了，不能在下移了');
      return false;
    }
    data.map((item1) => {
      if (item1._id == selectedRowKeys[0]) {
        item1.desc = newselectedRowKeys + 1;
        setnewselectedRowKeys(item1.desc);
      }
    });
    data.map((item2) => {
      if (newselectedRowKeys + 1 == item2.desc) {
        if (item2._id != selectedRowKeys[0]) {
          item2.desc = newselectedRowKeys;
        }
      }
    });
    data.sort((a, b) => {
      return a.desc - b.desc;
    });
    setdata([...data]);
  }
  // 存放头部显示几个导航的数据
  const [toptotal, settoptotal] = useState(16);
  // 获取显示几个头部导航
  function qutotal(e) {
    settoptotal(e);
  }

  const jumpMyMessage = () => {
    console.log();
    history.push('/home/MyMessage');
  };
  const jumpSetOrg = () => {
    history.push('/home/system/SetOrg');
  };
  // 修改密码表单
  const fromref = React.createRef();
  const onFinish = async (values) => {
    console.log('Success:', values);
    if (values.newpassword == values.pwd) {
      let userobj = {
        _id: userMessage._id,
        password: values.newpassword,
      };
      await axios.put(`http://127.0.0.1:7777/users/setpw`, userobj);
      alert('修改成功');
      window.sessionStorage.clear();
      return history.push('/login');
    } else {
      alert('两次密码不一致');
      setPassword(false);
      return;
    }
  };
  return (
    <div className="home">
      <Fragment>
        {/* 头部 */}
        <div className="home_header">
          <div className="header_left">
            <img src={require('./img/logo.png')} alt="" />
          </div>
          <div className="header_right">
            <ul className="menu">
              {/* {console.log(menulist)} */}

              {menulist.map((item, index) => {
                return (
                  <li
                    style={{ fontSize: 'lpx' }}
                    key={item._id}
                    onClick={() => {
                      if (item.MouduleName == '库存管理') {
                        history.push('/home/stock');
                      } else if (item.MouduleName == '销售管理') {
                        history.push('/home/sale');
                      } else if (item.MouduleName == '生产管理') {
                        history.push('/home/production');
                      } else if (item.MouduleName == '财务管理') {
                        history.push('/home/finance');
                      } else if (item.MouduleName == '采购管理') {
                        history.push('/home/purchase');
                      } else if (item.MouduleName == '流程') {
                        history.push('/home/flow/sponsor');
                      } else if (item.MouduleName == '报告') {
                        history.push('/home/report/daily');
                      } else if (item.MouduleName == '人事') {
                        history.push('/home/mymessage');
                      }
                      huanleftnav(item._id);
                    }}
                  >
                    <img src={require('./img' + item.imgpath)} alt="" />
                    <span>{item.MouduleName}</span>
                  </li>
                );
              })}
            </ul>
          </div>
        </div>
        {/* 中间主体部分 */}
        <div className="home_main">
          <div className="container">
            <div className="resizable"></div>
            <div className="content">
              <div className="userinfo" style={{ height: '100px' }}>
                <div className="userinfo_left">
                  <img
                    style={{
                      width: '80px',
                      height: '80px',
                      marginTop: '10px',
                      marginLeft: '10px',
                      marginRight: '10px',
                    }}
                    // src={require('./img' + item.imgpath)}
                    // src={require('./img' + userMessage.imgpath)}
                    src={`http://127.0.0.1:7777/${userMessage.imgpath}`}
                    alt=""
                  />
                </div>
                <div className="userinfo_right">
                  <p onClick={jumpMyMessage}>姓名：{userMessage.username}</p>
                  <p onClick={jumpSetOrg}>部门：总经办</p>
                  <p onClick={handTrue}>职位：总经理</p>
                </div>
              </div>
              <div className="leftnav">
                <div className="navTiTle">{navTitle}</div>
                <Menu
                  mode="inline"
                  openKeys={openKeys}
                  onOpenChange={onOpenChange}
                  style={{ width: '100%' }}
                  items={newitems}
                  onClick={pushxin}
                />
              </div>
            </div>
          </div>
          {/* 右边 echarts */}
          <div className="home_main_right">
            <div className="home_main_right_top">
              <ul>
                {menuTop.map((item) => {
                  return (
                    <li className="menutop" key={item.key}>
                      <span
                        className="menuname"
                        onClick={() => setProps(item.key)}
                      >
                        {item.name}
                      </span>
                      <span onClick={() => Ondelete(item.key)} className="x">
                        X
                      </span>
                    </li>
                  );
                })}
                <li className="menuRight">
                  <svg
                    onClick={() => {
                      setPassword(true);
                    }}
                    t="1675840299607"
                    className="icon"
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    p-id="3703"
                    width="200"
                    height="200"
                  >
                    <path
                      d="M418.133333 499.2c-21.333333-34.133333-29.866667-72.533333-29.866666-115.2 0-119.466667 93.866667-213.333333 213.333333-213.333333s213.333333 93.866667 213.333333 213.333333-93.866667 213.333333-213.333333 213.333333c-46.933333 0-85.333333-12.8-123.733333-38.4l-98.133334 98.133334 46.933334 46.933333-59.733334 59.733333-46.933333-46.933333-29.866667 29.866667 46.933334 46.933333L277.333333 853.333333 170.666667 746.666667l247.466666-247.466667zM601.6 256c-72.533333 0-128 55.466667-128 128s55.466667 128 128 128 128-55.466667 128-128-59.733333-128-128-128z"
                      fill="#444444"
                      p-id="3704"
                    ></path>
                  </svg>
                  <ExportOutlined onClick={loginout} />
                </li>
              </ul>
            </div>
            <div className="home_main_right_main">{children}</div>
          </div>
        </div>
        {/* 职位弹框 */}
        <div
          className="usersinfo"
          style={{ display: isModalOpen ? '' : 'none' }}
        >
          <div className="usersinfotop">
            <div>
              <img src={require('./img/tag_blue.png')} alt="" />
              <p>职位</p>
            </div>
            <div>
              <span className="usersinfotopch" onClick={yincang}>
                <UpOutlined />
              </span>
              <span className="usersinfotopcha" onClick={handFalse}>
                <CloseOutlined />
              </span>
            </div>
          </div>
          <div className={shousuo}>
            <div className="usertext1">
              <div className="text1">
                <span>岗位职责</span>
                <span>: </span>
              </div>
              <textarea className="text" cols="30" rows="10"></textarea>
            </div>
            <div className="usertext2">
              <div className="text2">
                <span>职责描述</span>
                <span>: </span>
              </div>
              <textarea className="text" cols="30" rows="10"></textarea>
            </div>
          </div>
        </div>

        {/* 管理弹框 */}
        <div
          className="logininfo1"
          style={{ display: isModalOpener ? '' : 'none' }}
        >
          <div className="logininfotop">
            <p>用户模块管理</p>
            <span className="logininfotopcha" onClick={handleClose}>
              <CloseOutlined />
            </span>
          </div>
          <div className="homeguanlitop">
            <ul>
              <li style={{ marginRight: '20px' }}>
                <button onClick={sahngyi}>上移</button>
              </li>
              <li style={{ marginRight: '20px' }}>
                <button onClick={xiayi}>下移</button>
              </li>
              <li style={{ marginRight: '60px' }}>
                <button onClick={baocun}>保存</button>
              </li>
              <li style={{ marginTop: '5px' }}>
                展示模块数：
                <InputNumber
                  style={{ width: '80px' }}
                  min={1}
                  max={16}
                  defaultValue={toptotal}
                  onChange={qutotal}
                />
              </li>
            </ul>
          </div>
          <div className="homeguantable">
            <Table
              columns={columns}
              // rowKey={(record) => record._id}
              pagination={false}
              dataSource={data}
              size="small"
              rowSelection={rowSelection}
              scroll={{ y: '325px' }}
            />
          </div>
        </div>
        {/* 消息图标 */}
        <div
          className="message"
          onClick={() => {
            history.push('/home/news');
          }}
        >
          <div
            className="badge"
            style={{ display: unreadMessage ? '' : 'none' }}
          >
            {unreadMessage}
          </div>
        </div>
        {/* 弹框部分 */}

        {/* 密码弹框 */}
        <div className="pwd" style={{ display: isPassword ? '' : 'none' }}>
          <div className="logininfotop">
            <p>修改密码</p>
            <span
              className="logininfotopcha"
              onClick={() => {
                setPassword(false);
              }}
            >
              <CloseOutlined />
            </span>
          </div>
          <div>
            <Form
              name="basic"
              labelCol={{
                span: 6,
              }}
              wrapperCol={{
                span: 17,
              }}
              style={{
                maxWidth: 400,
              }}
              initialValues={{
                remember: true,
              }}
              onFinish={onFinish}
              autoComplete="off"
            >
              <Form.Item label="用户名" name="username">
                <span>{userMessage.username}</span>
              </Form.Item>

              <Form.Item label="原密码" name="oldpassword">
                <Input.Password />
              </Form.Item>

              <Form.Item label="新密码" name="newpassword">
                <Input.Password />
              </Form.Item>
              <Form.Item label="确认密码" name="pwd">
                <Input.Password />
              </Form.Item>

              <Form.Item
                wrapperCol={{
                  offset: 6,
                  span: 16,
                }}
              >
                <Button className="but_pwd" type="primary" htmlType="submit">
                  保存
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </Fragment>
    </div>
  );
};
export default withRouter(Home);
